//
//  RoomListViewController.m
//  000-ChatChair
//
//  Created by 李晓东 on 2018/4/19.
//  Copyright © 2018年 PeanutXu. All rights reserved.
//

#import "RoomListViewController.h"
#import "AppDelegate.h"
#import "ChatViewController.h"
#import <KissXML/KissXML.h>
#define SCREEN_WIDTH UIScreen.mainScreen.bounds.size.width
@interface RoomListViewController () <XMPPRoomDelegate, RoomListDelegate, UITextFieldDelegate>
@property (nonatomic, strong) NSMutableArray *roomArray;
@property (nonatomic, strong) XMPPRoom *room;
@end

@implementation RoomListViewController{
    AppDelegate *_app;
}

- (void)loadView{
    [super loadView];
    _roomArray = [NSMutableArray array];
    _app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    _app.roomListDelegate = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [UIApplication sharedApplication].statusBarFrame.size.height;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"li"];
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
    [self.tableView setTableHeaderView:header];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 20, SCREEN_WIDTH - 30 * 2, 29)];
    [label setText:_app.xmppStream.myJID.user];
    [header addSubview:label];
    
    UITextField *roomField = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, SCREEN_WIDTH, 30)];
    [roomField setPlaceholder:@"创建聊天室"];
    [roomField setBorderStyle:UITextBorderStyleRoundedRect];
    [roomField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [header addSubview:roomField];
    
    // 查询 room 列表
    [self getRoomList];

}

- (void)getRoomList {
    DDXMLElement *iqElement = [DDXMLElement elementWithName:@"iq"];
    [iqElement addAttributeWithName:@"type" stringValue:@"get"];
    [iqElement addAttributeWithName:@"from" stringValue:[NSString stringWithFormat:@"%@%@", _app.xmppStream.myJID.user, HOST_SUFFIX]];
    [iqElement addAttributeWithName:@"to" stringValue:ROOM_SUFFIX];
    [iqElement addAttributeWithName:@"id" stringValue:GET_ROOMS_ID];
    
    DDXMLElement *queryElement = [DDXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/disco#items"];
    [iqElement addChild:queryElement];
    // xmppstream向服务器发起查询聊天室查询,在服务器返回响应时,会调用 xmppstream 的- xmppStream:didReceiveIQ方法
    [_app.xmppStream sendElement:iqElement];
    
}

- (void)listRooms:(DDXMLElement *)ele{
    NSArray *itemsArray = [ele elementsForName:@"item"];
    for (DDXMLElement *element in itemsArray) {
        [_roomArray addObject:[element attributeForName:@"jid"]];
    }
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void)joinRoom: (NSString *)jid {
    [self addRoom:jid];
}

- (void)addRoom:(NSString *)roomName {
    if (_app.roomStorage == nil) {
        _app.roomStorage = [[XMPPRoomCoreDataStorage alloc]init];
    }
    // ?指谁创建的
    XMPPJID *roomJid = [XMPPJID jidWithString:roomName];
    // 创建一个 聊天室
    _room = [[XMPPRoom alloc]initWithRoomStorage:_app.roomStorage jid:roomJid];
    // 建立聊天室和 xmppStream 的关联
    [_room activate:_app.xmppStream];
    [_room addDelegate:self delegateQueue:_app.queue];
    // 不管新建还是加入已有的聊天室
    [_room joinRoomUsingNickname:_app.xmppStream.myJID.user history:nil];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

   NSString *chatRoom = [textField.text containsString:ROOM_SUFFIX] ? chatRoom : [NSString stringWithFormat:@"%@%@", chatRoom, ROOM_SUFFIX];
    [self addRoom:chatRoom];
    return YES;
}

- (void)xmppRoomDidCreate:(XMPPRoom *)sender{
    
}

- (void)xmppRoomDidJoin:(XMPPRoom *)sender{
    NSLog(@"you in");
    ChatViewController *viewController = (ChatViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"chatScene"];
    [viewController setSession:_room.roomJID.full];
    [self presentViewController:viewController animated:YES completion:nil];
}

#pragma mark - Table view data source

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    CGFloat screenWidth = self.view.frame.size.width;
//    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 80)];
//    UILabel *tipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 26)];
//    tipsLabel setText:@"
//    return headerView;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _roomArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"li" forIndexPath:indexPath];
    DDXMLNode *node = _roomArray[indexPath.row];
    
    cell.textLabel.text = node.stringValue;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *chatRoom = _roomArray[indexPath.row];
    DDXMLNode *node = _roomArray[indexPath.row];
    [self joinRoom:node.stringValue];
    
    
    
}

@end
